const db = require('../common/basicConnection')
const sqlCommands = require('../common/sqlCommand')
const validate = require('../common/validate');
/**
 * 登录
 * @param {*} req 
 * @param {*} res 
 * @param {*} next 
 */
async function login(req, res, next) {
  // 获取前台页面传过来的参数
  var param = req.body
  if (validate.validateUse(param.username, res) && validate.validatePsd(param.password, res)) {
    try {
      const result = await db.queryall(sqlCommands.queryUser, [param.username]);
      if (result.length > 0) {
        if (result[0].password === param.password) {
          const save = await saveUser(req.session.id, param.username);
          console.log(save, '222222222222222')
          if (save) {
            req.session.isLogin = req.session.id;
          }
          res.json({
            code: 0,
            msg: '登录成功'
          })
        } else {
          res.json({
            code: 1,
            msg: '登录失败'
          })
        }
      } else {
        res.json({
          code: 1,
          msg: '用户名不存在'
        })
      }
    } catch (err) {
      console.log(err)
    }
  }
}
/**
 * 登出
 * @param {*} req 
 * @param {*} res 
 * @param {*} next 
 */
function loginOut(req, res, next) {
  req.session.destroy(function (err) {
    if (err) {
      res.json({
        code: 1,
        msg: '退出登录失败'
      })
    }
    console.log(req.session, "333")
    res.json({
      code: 0,
      msg: '退出成功'
    })
  })
  // req.session.user = null;
  // req.session.isLogin = false;
  // res.json({
  //     code: 0,
  //     msg: '登陆成功'
  // })    
}
/**
 * 注册
 * @param {*} req 
 * @param {*} res 
 * @param {*} next 
 */
function register(req, res, next) {
  var param = req.body
  if (validate.validateUse(param.username, res) && validate.validatePsd(param.password, res)) {
    db.queryArgs(sqlCommands.queryUser, [param.username], function (err, row) {
      console.log(row,'22222222222222') //查询的结果是数组
      if (row.length == 0) {
        db.queryArgs(sqlCommands.register, [param.username, param.password],
          function (err, result) {
            if (err) {
              throw new Error(err)
            } 
            if (result != undefined) { //新增的结果是对象
              res.json({
                code: 0,
                msg: '注册成功'
              })
            } else {
              res.json({
                code: 0,
                msg: '注册失败'
              })
            }
          })
      } else {
        res.json({
          code: 0,
          msg: '用户名已存在'
        })
      }
    })
  }
}
/**
 * 
 * 验证sessionid
 */
async function checkSid(id) {
  try {
    let result = await db.queryall(sqlCommands.getSid, [id]);
    if (result.length > 0) {
      return true
    } else {
      return false
    }
  } catch (err) {
    console.log(err)
  }
}
/**
 * 存session 和用户名
 * @param {*} sid  sessionid
 * @param {*} name 用户名
 */
async function saveUser(sid, name) {
  try {
    let search = await db.queryall(sqlCommands.getUser, [name]);  //session表中查用户名
    if (search.length > 0) {
      let update = await db.queryall(sqlCommands.updateSid, [sid, name]);
      console.log(update)  //更新的结果是对象
      if (update) {
        return true
      } else {
        return false
      }
    } else {
      let result = await db.queryall(sqlCommands.insertSession, [sid, name]);
      if (result) {
        return true
      } else {
        return false
      }
    }


  } catch (err) {
    console.log(err)
  }
}
module.exports = {
  login: login,
  loginOut: loginOut,
  register: register,
  checkSid: checkSid
}